import axios from 'axios'
import Qs from 'qs'
import router from '@/router'

const baseURL = ''
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }]
})

instance.interceptors.request.use(function (config) {
  // Do something before request is sent
  if (token) {
    config.token = token
  }
  // console.log(config)
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
instance.interceptors.response.use(function (response) {
  // Do something with response data
  if (response.data.errCode === 2) {
    router.push({
      path: '/',
      query: { redirect: router.currentRoute.fullPath }  // 从哪个页面跳转
    })
  }
  return response
}, function (error) {
  // Do something with response error
  // Message.error(error.message)
  return Promise.reject(error.response.data)
})

export default instance
